package com.itmuch.contentcenter.sentineltest;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.omg.CORBA.SystemException;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
public class MyUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        ErrorMsg errorMsg = null;
        if (e instanceof FlowException){
            errorMsg = ErrorMsg.builder()
                    .status(101)
                    .msg("降流了")
                    .build();
        }else if (e instanceof DegradeException){
            errorMsg = ErrorMsg.builder()
                    .status(102)
                    .msg("降级了")
                    .build();
        }else if (e instanceof SystemBlockException){
            errorMsg = ErrorMsg.builder()
                    .status(103)
                    .msg("系统降了")
                    .build();
        }else if (e instanceof ParamFlowException){
            errorMsg = ErrorMsg.builder()
                    .status(104)
                    .msg("参数流降级")
                    .build();
        }else if (e instanceof AuthorityException){
            errorMsg = ErrorMsg.builder()
                    .status(105)
                    .msg("权限降级")
                    .build();
        }
        httpServletResponse.setStatus(500);
        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(
                httpServletResponse.getWriter(),errorMsg
        );
    }
}

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
class ErrorMsg{

    Integer status;

    String msg;

}
